import * as xlsx from 'xlsx'
import type { WorkBook } from 'xlsx'
import type { JsonToSheet, AoAToSheet } from './type'

const { utils, writeFile } = xlsx

export const DEF_FILE_NAME = 'excel-list.xlsx'

export function jsonToSheetXlsx<T = any>({ data, header, filename = DEF_FILE_NAME, json2sheetOpts = {}, write2excelOpts = { bookType: 'xlsx' } }: JsonToSheet<T>) {
  const arrData = [...data]
  if (header) {
    arrData.unshift(header)
    json2sheetOpts.skipHeader = true
  }

  const worksheet = utils.json_to_sheet(arrData, json2sheetOpts)

  /* add worksheet to workbook */
  const workbook: WorkBook = {
    SheetNames: [filename],
    Sheets: {
      [filename]: worksheet
    }
  }
  /* output format determined by filename */
  writeFile(workbook, filename, write2excelOpts)
  /* at this point, out.xlsb will have been downloaded */
}

export function aoaToSheetXlsx<T = any>({ data, header, filename = DEF_FILE_NAME.split('.')[0], write2excelOpts = { bookType: 'xlsx' } }: AoAToSheet<T>) {
  const arrData = [...data]
  if (header) {
    arrData.unshift(header)
  }

  const worksheet = utils.aoa_to_sheet(arrData)

  /* add worksheet to workbook */
  const workbook: WorkBook = {
    SheetNames: [filename],
    Sheets: {
      [filename]: worksheet
    }
  }
  /* output format determined by filename */
  writeFile(workbook, filename, write2excelOpts)
  /* at this point, out.xlsb will have been downloaded */
}

/**
 * 将数据导出到文件中
 * @param data 待导出的数据
 * @param params 导出数据需要的参数
 */
export const dataToFile = (data, params) => {
  console.log(data)
  const customData: any = []
  if (params.headerType === 'custom') {
    let header = null
    const headerSort = params.sort
    if (params.headerType === 'custom') {
      header = params.header
    }
    data.forEach(item => {
      const itemObj = {}
      headerSort.forEach(current => {
        itemObj[current] = item[current]
      })
      customData.push(itemObj)
    })
    jsonToSheetXlsx({
      data: customData,
      header: header,
      filename: params.filename,
      json2sheetOpts: {
        // 指定顺序
        header: headerSort
      },
      write2excelOpts: {
        bookType: params.fileType
      }
    })
  } else {
    jsonToSheetXlsx({
      data: customData,
      filename: params.filename,
      write2excelOpts: {
        bookType: params.fileType
      }
    })
  }
}
